import React, { useEffect, useState } from 'react';
import {
  Form,
  Modal,
  DatePicker,
  Select,
  Checkbox,
  Table,
  Tag,
  Tooltip,
  Button,
  message,
} from 'antd';
import { activityDetail, activityBigTc, activityExportLate } from '@/services/operate';
import { CaretUpOutlined, CaretDownOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { uniqBy, debounce, isEmpty } from 'lodash';
import styles from './style.less';

type Props = {
  visibleModel: boolean;
  dataModel: string;
  segmentValue: string;
};

let dataTableBro: any = [];
const TooltipTitle = {
  rankValue: 'Rank Value  = TC Mix% * SPT',
  tcMix: '体量规模：TC Mix% = 券核销TC/pre-order或delivery大盘TC',
  spt: '质量：SPT = 券核销整单Sales/券在卡包曝光UV',
};

const CalendarModel: React.FC<Props> = ({ visibleModel, dataModel, segmentValue }) => {
  console.log('dataModel', dataModel);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [modalForm] = Form.useForm();
  const dateWatch = Form.useWatch('date', modalForm);
  const channelIdWatch = Form.useWatch('channelId', modalForm);
  const onlyOpenPlaceWatch = Form.useWatch('onlyOpenPlace', modalForm);
  const rangeWatch = Form.useWatch('range', modalForm);
  const [visible, setVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [loading, setLoading] = useState(false);
  const [btnloading, setBtnLoading] = useState(false);
  const [bigTc, setBigTc] = useState<any>(0);
  // 切换活动效果时，需要重置的有： pageNo\scrollFlag
  const [pageNo, setPageNo] = useState(1); // 活动效果--虚拟滚动的分页
  const [scrollFlag, setSrollFlag] = useState(true); // 是否展示--虚拟滚动
  const [sortMap, setSortMap] = useState<any>({ rankValue: false }); // 排序默认rankvalue降序排序

  const resetValue = () => {
    dataTableBro = [];
    setPageNo(1);
    setSrollFlag(true);
    // setVisible(true);
  };

  const queryActivityBigTc = async (param: any) => {
    const { code, data } = await activityBigTc(param);
    if (code === 200) {
      setBigTc(data);
    }
  };

  const initQuery = async (isAddPageNo?: boolean, isResetSort?: boolean) => {
    // 吊接口用
    const valueForm = modalForm.getFieldsValue();
    console.log(valueForm);
    const param: any = {
      date: moment(valueForm.date).format('YYYY-MM-DD'),
      channelId: valueForm.channelId || 'CPOS',
      onlyOpenPlace: valueForm.onlyOpenPlace && valueForm.onlyOpenPlace.length > 0 ? true : false,
      pageNo: isAddPageNo && isAddPageNo === true ? pageNo + 1 : 1,
      // pageNo: 1,
      pageSize: 50,
    };
    if (valueForm.range && valueForm.range.length > 0) {
      param.startTime = valueForm.range[0] ? moment(valueForm.range[0]).format('YYYY-MM-DD') : '';
      param.endTime = valueForm.range[1] ? moment(valueForm.range[1]).format('YYYY-MM-DD') : '';
    }
    // 取对象的第一个键位和值;
    if (!isEmpty(sortMap)) {
      const firstKey = Object.keys(sortMap)[0];
      param.sortField = firstKey;
      param.reverseOrder = sortMap[firstKey] === true ? false : true;
    } else {
      param.sortField = 'rankValue';
      param.reverseOrder = true;
    }

    queryActivityBigTc(param);
    setLoading(true);
    const { code, data } = await activityDetail(param);
    setLoading(false);
    if (code === 200 && data) {
      dataTableBro = uniqBy([...dataTableBro, ...data.rows], 'id');
      setDataSource(dataTableBro);
      setPageNo(data.pageNo);
      if (data.totalPage > data.pageNo) {
        setSrollFlag(true);
      } else {
        setSrollFlag(false);
      }
    }
  };

  useEffect(() => {
    if (visibleModel) {
      setVisible(true);
      modalForm.setFieldsValue({
        date: dataModel ? moment(dataModel) : null,
        channelId: segmentValue === '2' ? 'CPOS' : 'Delivery',
        onlyOpenPlace: ['仅显示打开卡包券'],
      });
      setTimeout(() => {
        resetValue();
        initQuery();
      });
    }
  }, [visibleModel]);

  useEffect(() => {
    setSortMap({});
    resetValue();
    setTimeout(() => {
      initQuery(false, true);
    });
  }, [dateWatch, onlyOpenPlaceWatch, channelIdWatch, rangeWatch]);

  useEffect(() => {
    if (!isEmpty(sortMap)) {
      initQuery();
    }
  }, [sortMap]);

  const handleClose = () => {
    resetValue();
    setVisible(false);
    setDataSource([]);
    setSelectedRowKeys([]);
  };

  const customTitleAction = (name: string, type: string) => {
    return (
      <div style={{ display: 'flex' }}>
        {name}
        {['rankValue', 'tcMix', 'spt'].includes(type) && (
          // @ts-ignore
          <Tooltip title={TooltipTitle[type]}>
            <QuestionCircleOutlined style={{ color: '#bfbfbf', marginLeft: 4, marginBottom: 2 }} />
          </Tooltip>
        )}
        <div
          style={{ display: 'flex', flexDirection: 'column', marginLeft: 10, cursor: 'pointer' }}
        >
          <CaretUpOutlined
            style={{ color: sortMap[type] === true ? '#ec4848' : '#bfbfbf' }}
            onClick={() => {
              setSortMap({
                [type]: true,
              });
              resetValue();
            }}
          />
          <CaretDownOutlined
            style={{ color: sortMap[type] === false ? '#ec4848' : '#bfbfbf' }}
            onClick={() => {
              setSortMap({
                [type]: false,
              });
              resetValue();
            }}
          />
        </div>
      </div>
    );
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      type: 'index',
      width: 60,
      render: (text: any, record: any, index: number) => (
        <div style={{ display: 'flex' }}>
          {/* {index === dataTableBro.length - 1 ? <div ref={divRef}>最后</div> : null} */}
          <span style={{ marginLeft: 10 }}>{index + 1}</span>
          {record.couponSortPlan && (
            <Tooltip
              placement="top"
              title={
                <>
                  <div>{record.couponSortPlan.planName}</div>
                  <div>
                    生效时间：
                    {record.couponSortPlan.startTime + '-' + record.couponSortPlan.endTime}
                  </div>
                  <div>更新时间：{record.couponSortPlan.updatedAt}</div>
                  <div>更新人：{record.couponSortPlan.updatedBy}</div>
                </>
              }
            >
              <Tag color={'red'} style={{ position: 'absolute', top: 0, left: 74, zIndex: 999 }}>
                已置顶
              </Tag>
            </Tooltip>
          )}
        </div>
      ),
    },
    {
      title: '活动定义',
      dataIndex: 'activityId',
      key: 'activityId',
      width: 155,
      ellipsis: true,
      align: 'left',
    },
    {
      title: 'Campaign Code',
      dataIndex: 'campaignCode',
      key: 'campaignCode',
      width: 145,
      ellipsis: true,
      align: 'left',
    },
    {
      title: '活动有效期',
      dataIndex: 'validStartTime',
      key: 'validStartTime',
      width: 300,
      ellipsis: true,
      align: 'left',
      render: (text: any, record: any) => (
        <>
          {record.activityStartTime}-{record.activityEndTime}
        </>
      ),
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      key: 'activity',
      width: 305,
      ellipsis: true,
      align: 'left',
    },
    {
      title: customTitleAction('Rank value', 'rankValue'),
      dataIndex: 'rankValue',
      key: 'rankValue',
      width: 140,
      ellipsis: true,
      align: 'left',
    },
    {
      title: customTitleAction('TC Mix%', 'tcMix'),
      dataIndex: 'tcMix',
      key: 'tcMix',
      width: 120,
      ellipsis: true,
      align: 'left',
      render: (text: any, record: any) => (
        <>{record.tcMix ? Number(Number(record.tcMix) * 100).toFixed(4) : 0}%</>
      ),
    },
    {
      title: customTitleAction('SPT', 'spt'),
      dataIndex: 'spt',
      key: 'spt',
      width: 100,
      ellipsis: true,
      align: 'left',
    },
    {
      title: customTitleAction('券核销TC', 'usedTc'),
      dataIndex: 'usedTc',
      key: 'usedTc',
      width: 120,
      ellipsis: true,
      align: 'left',
      render: (text: any, record: any) => <>{record.usedTc ? record.usedTc.toLocaleString() : 0}</>,
    },
    {
      title: customTitleAction('券核销连带Sales', 'usedSales'),
      dataIndex: 'usedSales',
      key: 'usedSales',
      width: 145,
      ellipsis: true,
      align: 'left',
      render: (text: any, _: any) => <>{_.usedSales ? Number(_.usedSales).toLocaleString() : 0}</>,
    },
    {
      title: customTitleAction('曝光UV', 'uv'),
      dataIndex: 'uv',
      key: 'uv',
      width: 100,
      ellipsis: true,
      align: 'left',
      render: (text: any, record: any) => <>{record.uv ? record.uv.toLocaleString() : 0}</>,
      // render: (text: any, record: any) => <>{record.uv.toLocaleString()}</>,
    },
  ];

  const debouncedHandle = debounce(() => {
    // 在这里执行你想要的操作
    if (scrollFlag) {
      initQuery(true);
    }
  }, 500);

  const handleScroll = (event: any) => {
    const element = event.target;
    const heightBro = element.scrollHeight - element.scrollTop;
    if (heightBro - element.clientHeight < 2) {
      if (scrollFlag) {
        debouncedHandle();
      }
    }
  };

  const rowSelection = {
    // fixed: true,
    columnWidth: 60,
    selectedRowKeys,
    onSelect: (record: any, selected: any, selectedRows: any) => {
      setSelectedRowKeys(selectedRows.map((item: any) => item.id));
    },
    onSelectAll: (_status: boolean, selectedRowsSelect: any[]) => {
      setSelectedRowKeys(selectedRowsSelect.map((item: any) => item.id));
    },
  };

  const exportExcel = async () => {
    console.log('selectedRowKeys', selectedRowKeys);

    try {
      const valueForm = modalForm.getFieldsValue();
      const param: any = {
        date: moment(valueForm.date).format('YYYY-MM-DD'),
        channelId: valueForm.channelId || 'CPOS',
        onlyOpenPlace: valueForm.onlyOpenPlace && valueForm.onlyOpenPlace.length > 0 ? true : false,
      };
      if (valueForm.range && valueForm.range.length > 0) {
        param.startTime = valueForm.range[0] ? moment(valueForm.range[0]).format('YYYY-MM-DD') : '';
        param.endTime = valueForm.range[1] ? moment(valueForm.range[1]).format('YYYY-MM-DD') : '';
      }
      // 非全部选择
      if (selectedRowKeys.length < dataSource.length) {
        const rankDataActivityVoListBro: any[] = [];
        dataSource.forEach((item: any) => {
          if (selectedRowKeys.includes(item.id)) {
            rankDataActivityVoListBro.push(item);
          }
        });
        param.rankDataActivityVoList = rankDataActivityVoListBro;
      }
      setBtnLoading(true);
      const resUpdate: any = await activityExportLate({ ...param });
      setBtnLoading(false);
      const url = window.URL.createObjectURL(resUpdate.data);
      const link = document.createElement('a');
      link.style.display = 'none';
      const Disposition = resUpdate?.Disposition || '';
      if (!Disposition) {
        message.error('暂无数据');
        return;
      }
      link.download = decodeURIComponent(Disposition?.split(`filename=`)[1]) || '导出文件'; // 下载的文件名称
      link.href = url;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  const onScrollCapture = () => {
    // 滚动的容器
    const tableEleNodes = document.querySelectorAll(`.tableRect .ant-table-body`)[0];
    if (
      Math.round(tableEleNodes?.scrollTop) + tableEleNodes?.clientHeight >
      tableEleNodes?.scrollHeight - 2
    ) {
      if (scrollFlag) {
        debouncedHandle();
      }
    }
  };

  return (
    <Modal
      maskClosable={false}
      width={1000}
      title={null}
      open={visible}
      footer={null}
      onCancel={handleClose}
    >
      <div className={styles['model-wrap']}>
        <Form
          labelCol={{ span: 5 }}
          form={modalForm}
          initialValues={{
            date: dataModel ? moment(dataModel) : null,
            channelId: 'CPOS',
            onlyOpenPlace: ['仅显示打开卡包券'],
          }}
        >
          <div className={styles['model-top']}>
            <div className={styles['top-left']}>
              <Form.Item label={null} name="date" style={{ marginRight: 30 }}>
                <DatePicker />
              </Form.Item>
              <Form.Item label={null} name="channelId" style={{ width: 130, marginRight: 30 }}>
                <Select
                  options={[
                    {
                      value: 'CPOS',
                      label: '堂食',
                    },
                    {
                      value: 'Delivery',
                      label: '外送',
                    },
                  ]}
                />
              </Form.Item>
              <Form.Item label={null} name="range" style={{ width: 240 }}>
                <DatePicker.RangePicker />
              </Form.Item>
            </div>
            <div style={{ color: '#ec4848', fontSize: 16, fontWeight: 600 }}>
              大盘TC:{bigTc?.toLocaleString() || 0}
            </div>
            <div className={styles['top-right']}>
              <Form.Item label={null} name="onlyOpenPlace">
                <Checkbox.Group
                  options={[
                    {
                      value: '仅显示打开卡包券',
                      label: '仅显示打开卡包券',
                    },
                  ]}
                />
              </Form.Item>
            </div>
          </div>
        </Form>
        <div style={{ display: 'flex', justifyContent: 'right' }}>
          <Button
            disabled={selectedRowKeys.length === 0}
            style={{ marginBottom: 16, marginTop: -8 }}
            type="primary"
            key="out"
            onClick={() => {
              exportExcel();
            }}
            loading={btnloading}
          >
            导出数据
          </Button>
        </div>
        {/* onScroll={handleScroll} */}
        <div className={styles['table-wrap']} onScrollCapture={onScrollCapture}>
          <Table
            className={'tableRect'}
            id="id"
            rowKey="id"
            rowSelection={rowSelection}
            dataSource={dataSource}
            // @ts-ignore
            columns={columns}
            scroll={{ x: 800, y: 350 }}
            pagination={false}
            loading={loading}
          />
        </div>
      </div>
    </Modal>
  );
};

export default CalendarModel;
